package com.dflc.controller.BackManageController;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.SysDataPermission;
import com.dflc.entity.po.TBackLoginUser;
import com.dflc.entity.po.UUnit;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.UnitPageReq;
import com.dflc.entity.req.UunitReq;
import com.dflc.entity.vo.UUnitVo;
import com.dflc.entity.vo.UUnitVo2;
import com.dflc.mapper.SysDataPermissionMapper;
import com.dflc.mapper.TBackLoginUserMapper;
import com.dflc.mapper.UUnitMapper;
import com.dflc.service.SysDataPermissionService;
import com.dflc.service.TBackLoginUserService;
import com.dflc.service.UUnitService;
import com.dflc.utils.EntityUtils;
import com.dflc.utils.PageEntity;
import com.dflc.utils.PageEntityBuilder;
import com.dflc.utils.PageRequestEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户单位业务操作
 *
 * @author tqx
 * @version 1.0.0.0
 * <p>Title: UnitController </p >
 * <p>Description: 用户单位业务操作  </p >
 * Package: com.dlfc.controller
 * Date: 2024年12月30日 17:10
 */
@RestController
@Slf4j
@RequestMapping("/unit")
public class UnitController {


    @Resource
    public UUnitService uUnitService;


    @Resource
    public UUnitMapper uUnitMapper;
    @Resource
    private TBackLoginUserService tBackLoginUserService;
    @Resource
    private TBackLoginUserMapper tBackLoginUserMapper;
    @Resource
    public SysDataPermissionService sysDataService;
    @Resource
    public SysDataPermissionMapper sysDataMapper;

    /**
     * 分页查询单位/负责部门
     * @return HttpResponseEntity
     * @author tqx
     * @date 2024/12/30 17:14
     * Description:[getUnitByPage]
     */
    @PostMapping("/getUnitByPage")
    public HttpResponseEntity getUnitByPage(@RequestBody PageRequestEntity page) {
        try{
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser sysLoginUser = tBackLoginUserService.getById(id3);
            if (sysLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().intValue()==CommonConstant.StateActive.Deleted.intValue()) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            if (sysLoginUser.getIsAdmin().intValue()!=CommonConstant.BackIsAdmin.Yes.intValue()){
                //不是超级管理员不能操作
                return HttpResponseEntity.error(500,"没有权限!");
            }
            UnitPageReq req = new UnitPageReq();
            req.setCurrent(page.getCurrentPage());
            req.setSize(page.getPageSize());
            if (!ObjectUtils.isEmpty(page.getSort()) && page.getSort().get(0).getType()!=null){
                req.setOrders(EntityUtils.sort(page));
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitAllName"))){
                req.setUnitAllName(page.getQuery().get("unitAllName").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitForShort"))){
                req.setUnitForShort(page.getQuery().get("unitForShort").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitLeader"))){
                req.setUnitLeader(page.getQuery().get("unitLeader").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitHead"))){
                req.setUnitHead(page.getQuery().get("unitHead").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitContact"))){
                req.setUnitContact(page.getQuery().get("unitContact").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitContactPhone"))){
                req.setUnitContactPhone(page.getQuery().get("unitContactPhone").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitAddress"))){
                req.setUnitAddress(page.getQuery().get("unitAddress").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitType"))){
                req.setUnitType(page.getQuery().get("unitType").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("state"))){
                req.setState(Integer.valueOf(page.getQuery().get("state").toString()));
            }
            Page<UUnit> page1 = uUnitMapper.pageQuery(req);
            PageEntity entity = PageEntityBuilder.builder()
                    .data(page1.getRecords())
                    .currentPage(page1.getCurrent())
                    .pageSize(page1.getSize())
                    .totalCount(page1.getTotal())
                    .totalPage(page1.getPages())
                    .build();
            return HttpResponseEntity.success(entity);
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


    /**
     * 查询业主单位(懒加载)
     *
     * @return SciaiHttpResponseEntity
     * @author tqx
     * @param page
     * @date 2023/4/19 11:42
     * Description:[getNewDictionaryEntriesByType ]
     */
    @PostMapping("/getUnitByLazy")
    public HttpResponseEntity getUnitByLazy(@RequestBody PageRequestEntity page) {
        try {
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser sysLoginUser = tBackLoginUserService.getById(id3);
            if (sysLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().intValue()==CommonConstant.StateActive.Deleted.intValue()) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
//            if (sysLoginUser.getIsAdmin().intValue()!=CommonConstant.BackIsAdmin.Yes.intValue()){
//                //不是超级管理员不能操作
//                return HttpResponseEntity.error(500,"没有权限!");
//            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitAllName")) || !ObjectUtils.isEmpty(page.getQuery().get("unitForShort"))){
                Map<String, String> params2 = new HashMap<>();
                if (!ObjectUtils.isEmpty(page.getQuery().get("unitAllName"))){
                    params2.put("unitAllName",page.getQuery().get("unitAllName").toString());
                }
                if (!ObjectUtils.isEmpty(page.getQuery().get("unitForShort"))){
                    params2.put("unitForShort",page.getQuery().get("unitForShort").toString());
                }
                List<UUnitVo2> list2 = uUnitService.getAllTree2(params2);
                return HttpResponseEntity.success(list2);
            }else {
                Integer node=0;
                node = Integer.parseInt(page.getQuery().get("node").toString());
                List<UUnitVo2> list = uUnitService.getAllTree(node);
                return HttpResponseEntity.success(list);
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }

    }




    /**
     * 查询业主单位(懒加载)分页
     *
     * @return SciaiHttpResponseEntity
     * @author tqx
     * @param page
     * @date 2023/4/19 11:42
     * Description:[getUnitByLazyAndPage ]
     */
    @PostMapping("/getUnitByLazyAndPage")
    public HttpResponseEntity getUnitByLazyAndPage(@RequestBody PageRequestEntity page) {
        try {
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser sysLoginUser = tBackLoginUserService.getById(id3);
            if (sysLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().intValue()==CommonConstant.StateActive.Deleted.intValue()) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            if (sysLoginUser.getIsAdmin().intValue()!=CommonConstant.BackIsAdmin.Yes.intValue()){
                //不是超级管理员不能操作
                return HttpResponseEntity.error(500,"没有权限!");
            }

            UnitPageReq req = new UnitPageReq();
            req.setCurrent(page.getCurrentPage());
            req.setSize(page.getPageSize());

            if (!ObjectUtils.isEmpty(page.getQuery().get("unitAllName")) || !ObjectUtils.isEmpty(page.getQuery().get("unitForShort"))){
                Map<String, String> params2 = new HashMap<>();
                if (!ObjectUtils.isEmpty(page.getQuery().get("unitAllName"))){
                    params2.put("unitAllName",page.getQuery().get("unitAllName").toString());
                    req.setUnitAllName(page.getQuery().get("unitAllName").toString());
                }
                if (!ObjectUtils.isEmpty(page.getQuery().get("unitForShort"))){
                    params2.put("unitForShort",page.getQuery().get("unitForShort").toString());
                    req.setUnitForShort(page.getQuery().get("unitForShort").toString());
                }
                Page<UUnitVo2> page1 = uUnitMapper.findAllByMap3AndPage(req);
                List<UUnitVo2>  list = page1.getRecords();
                List<UUnitVo2> list1 = new ArrayList<>();
                //把list集合按照parentId字段进行分组，用stream流处理
                Map<Integer, List<UUnitVo2>> map = list.stream().collect(Collectors.groupingBy(UUnitVo2::getParentId));
                //把map集合按照key的升序排序
                Map<Integer, List<UUnitVo2>> sortMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                //遍历map
                for (Map.Entry<Integer, List<UUnitVo2>> entry : sortMap.entrySet()) {
                    //获取key
                    Integer key = entry.getKey();
                    //获取value
                    List<UUnitVo2> value = entry.getValue();
                    if (key.intValue()==0){
                        //是根
                        //遍历value
                        for (UUnitVo2 treeVo : value){
                            list1.add(treeVo);
                        }
                    }else {
                        //不是根则判断list1里面有没有
                        if (!ObjectUtils.isEmpty(list1) && list1.size()>0){
                            boolean a  =   uUnitService.findParentId(list1,key,value);
                            if (a){
                                continue;
                            }else {
                                //没有则遍历value
                                for (UUnitVo2 treeVo : value){
                                    list1.add(treeVo);
                                }
                            }
                        }else {
                            //没有则遍历value
                            for (UUnitVo2 treeVo : value){
                                list1.add(treeVo);
                            }
                        }

                    }
                }
                //把集合list1按照sort的升序排序
                list1.sort(Comparator.comparing(UUnitVo2::getSort));

                PageEntity entity = PageEntityBuilder.builder()
                        .data(list1)
                        .currentPage(page1.getCurrent())
                        .pageSize(page1.getSize())
                        .totalCount(page1.getTotal())
                        .totalPage(page1.getPages())
                        .build();
                return HttpResponseEntity.success(entity);
            }else {
                Integer node=0;
                node = Integer.parseInt(page.getQuery().get("node").toString());
                req.setParentId(node);
                Page<UUnitVo2> page1 = uUnitMapper.findAllByMap2AndPage(req);
                List<UUnitVo2>  list = page1.getRecords();
                for (UUnitVo2 treeVo : list){
                    //判断是否有下级
                    Map<String, Object> params2 = new HashMap<>();
                    params2.put("parentId",treeVo.getId());
                    List<UUnitVo2>  list2 = uUnitMapper.findAllByMap2(params2);
                    if (list2.size()>0){
                        treeVo.setIsChild(true);
                    }else {
                        treeVo.setIsChild(false);
                    }
                }
                //把list按照sort 的升序排序
                list.sort(Comparator.comparing(UUnitVo2::getSort));
                PageEntity entity = PageEntityBuilder.builder()
                        .data(list)
                        .currentPage(page1.getCurrent())
                        .pageSize(page1.getSize())
                        .totalCount(page1.getTotal())
                        .totalPage(page1.getPages())
                        .build();
                return HttpResponseEntity.success(entity);
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }

    }

    /**
     * 新增/修改单位
     * @param unit
     * @return HttpResponseEntity
     * @author tqx
     * @date 2025/2/7 10:42
     * Description:新增/修改单位
     */
    @PostMapping("/addOrUpdateUnit")
    public HttpResponseEntity addOrUpdateUnit(@RequestBody UUnit unit) {
        try {
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(id3);
            if (tBackLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }
            if (tBackLoginUser.getIsAdmin().intValue()!=CommonConstant.BackIsAdmin.Yes.intValue()){
                //不是超级管理员不能操作
                return HttpResponseEntity.error(500,"没有权限!");
            }
            //判断新增/修改时候单位名字是否有重复有效的
            Map<String, Object> params1 = new HashMap<>();
            if (ObjectUtils.isEmpty(unit.getUnitAllName()) || ObjectUtils.isEmpty(unit.getUnitForShort())){
                return HttpResponseEntity.error(500, "单位全称和单位简称不能为空!");
            }
            params1.put("unitAllName",unit.getUnitAllName());
            params1.put("unitForShort",unit.getUnitForShort());
            List<UUnitVo2>  list1 = uUnitMapper.findAllByMap2(params1);
            if (ObjectUtils.isEmpty(unit.getId())){
                //是新增
                if (!ObjectUtils.isEmpty(list1) && list1.size()>0){
                    return HttpResponseEntity.error(500, "单位全称和单位简称其一存在!");
                }
            }else {
                //是修改
                if (!ObjectUtils.isEmpty(list1) && list1.size()>0){
                    for (UUnitVo2 uUnitVo2 : list1) {
                        if (uUnitVo2.getId().intValue()!=unit.getId().intValue()){
                            return HttpResponseEntity.error(500, "单位全称和单位简称其一存在!");
                        }
                    }
                }
            }
            UUnit uUnit2 = new UUnit();
            BeanUtils.copyProperties(unit,uUnit2);
            uUnitService.saveOrUpdate(unit);
            //如果是新增则要同步生成对应的本级单位的数据权限
            if (ObjectUtils.isEmpty(uUnit2.getId()) && unit.getUnitType().equals(CommonConstant.unitType.Unit)){
                List<SysDataPermission> list2 =   new ArrayList<>();
                SysDataPermission sysData = new SysDataPermission();
                sysData.setBusinessName("unitId");
                sysData.setName(unit.getUnitForShort()+"本级");
                sysData.setCode(unit.getId().toString());
                sysData.setUnitId(unit.getId());
                list2.add(sysData);
                sysDataService.saveBatch(list2);
            }else if (!ObjectUtils.isEmpty(uUnit2.getId()) && unit.getUnitType().equals(CommonConstant.unitType.Unit)){
                //是修改则要同步修改对应的本级单位的数据权限(PC\微信两端)
                //查询该单位是否已经有数据权限
                Map<String, Object> params5 = new HashMap<>();
                params5.put("unitId", unit.getId());
                List<SysDataPermission> list5 = sysDataMapper.findAllByMap(params5);
                if (!ObjectUtils.isEmpty(list5) && list5.size() > 0) {
                    for (SysDataPermission sysData: list5){
                        sysData.setName(unit.getUnitForShort()+"本级");
                    }
                    sysDataService.saveOrUpdateBatch(list5);
                }
            }
            return HttpResponseEntity.success("操作成功!");
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 删除单位/负责部门
     * @author tqx
     * @date 2025/2/7 10:30
     * Description:  删除单位/负责部门
     * @param id
     * @return HttpResponseEntity
     */
    @DeleteMapping("/deleteUnit/{id}")
    public HttpResponseEntity deleteUnit(@PathVariable("id") String id) {
        try{
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(id3);
            if (tBackLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }
            if (tBackLoginUser.getIsAdmin().intValue()!=CommonConstant.BackIsAdmin.Yes.intValue()){
                //不是超级管理员不能操作
                return HttpResponseEntity.error(500,"没有权限!");
            }
            List<String> stringList = Arrays.asList(id.split(","));
            List<Integer> integerList = new ArrayList<>();
            for (String s : stringList) {
                integerList.add(Integer.valueOf(s));
            }
            List<UUnit> tUnits = uUnitService.list(new QueryWrapper<UUnit>().in("id", integerList));
            if (ObjectUtils.isEmpty(tUnits)) {
                return HttpResponseEntity.error(500, "单位不存在");
            }
            //还得查询看选择删除的单位是不是有下级
            Map<String, Object> params2 = new HashMap<>();
            params2.put("parentIds",integerList);
            params2.put("state",CommonConstant.StateActive.Active);
            List<UUnit> list1 = uUnitMapper.findAllByMap(params2);
            if (!ObjectUtils.isEmpty(list1) && list1.size()>0){
                Integer  parentId=list1.get(0).getParentId();
                for (UUnit uUnit : tUnits) {
                    if (uUnit.getId().intValue()==parentId.intValue())
                        return HttpResponseEntity.error(500, uUnit.getUnitAllName()+"该单位存在下级单位，不能删除!");
                }
            }
            //再判断删除单位是否有有效的账号，有则不能删除
            Map<String, Object> params3 = new HashMap<>();
            params3.put("unitIds",integerList);
            params3.put("state",CommonConstant.StateActive.Active);
            List<TBackLoginUser> tBackLoginUsers = tBackLoginUserMapper.findAllByMap(params3);
            if (!ObjectUtils.isEmpty(tBackLoginUsers) && tBackLoginUsers.size()>0){
                return HttpResponseEntity.error(500, "该单位存在有效账号，不能删除!");
            }

            for (UUnit tUnit : tUnits){
                tUnit.setState(CommonConstant.StateActive.Deleted);
            }

            //查询该单位是否已经有数据权限
            Map<String, Object> params = new HashMap<>();
            params.put("unitIds", integerList);
            List<SysDataPermission> list = sysDataMapper.findAllByMap(params);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                return HttpResponseEntity.error(500, "选中的单位下有数据权限，不能删除");
            }
            uUnitService.saveOrUpdateBatch(tUnits);
            return HttpResponseEntity.success("操作成功!");
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 获得单位/部门科室的下拉框
     * @author tqx
     * @date 2025/3/3 10:30
     * Description:  获得单位/部门科室的下拉框
     * @param uunitReq
     * @return HttpResponseEntity
     */
    @PostMapping("/getUnitSelect")
    public HttpResponseEntity getUnitSelect(@RequestBody UunitReq uunitReq) {
        try{
            List<UUnitVo> list  = uUnitService.getUnitSelect(uunitReq.getKey());
            return HttpResponseEntity.success(list);
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 查询科室
     * @author tqx
     * @date 2025/5/23 13:30
     * Description:  查询科室
     * @param parentId
     * @return HttpResponseEntity
     */
    @GetMapping("/getUnitSelectByUnitId/{parentId}")
    public HttpResponseEntity getUnitSelectByUnitId(@PathVariable("parentId") Integer parentId) {
        try{
            Map<String, Object> params4 = new HashMap<>();
            params4.put("parentId", parentId);
            params4.put("state", CommonConstant.StateActive.Active);
            List<UUnit> uUnits = uUnitMapper.findAllByMap(params4);
            List<Map<String,Object>> mapList =new ArrayList<>();
            for (UUnit uUnit : uUnits) {
                Map<String,Object> map = new HashMap<>();
                map.put("id",uUnit.getId());
                map.put("name",uUnit.getUnitAllName());
                mapList.add(map);
            }
            return HttpResponseEntity.success(mapList);
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


    /**
     * 查询用户单位数据字典格式
     * @author tqx
     * @date 2025/4/25 11:21
     * Description: 查询用户单位数据字典格式
     * @return HttpResponseEntity
     */
    @PostMapping("/getAllUnit")
    public HttpResponseEntity getAllUnit() {
        try{
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser sysLoginUser = tBackLoginUserService.getById(id3);
            if (sysLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().intValue()==CommonConstant.StateActive.Deleted.intValue()) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
//            if (sysLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0){
//                //不是超级管理员不能操作
//                return HttpResponseEntity.error(500,"没有权限!");
//            }
            List<Map<String,Object>> maps =new ArrayList<>();
            //查询所有有效的用户单位
            List<UUnit> list = uUnitService.list(new QueryWrapper<UUnit>().eq("state",CommonConstant.StateActive.Active)
                            .eq("unit_type",CommonConstant.unitType.Unit)
                    .orderByAsc("sort"));
            for (UUnit vo : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("id",vo.getId());
                map.put("name",vo.getUnitForShort());
                maps.add(map);
            }
            return HttpResponseEntity.success(maps);
        }catch (Exception e){
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

}
